<?php
/**
 * Created by PhpStorm.
 * User: Tangyijun
 * Date: 2017/3/14
 * Time: 14:21
 * 权限管理
 */
namespace app\admin\controller;
use app\data\Data;
use app\validate\RuleValidate;
use think\Config;
use think\Request;

/**
 * +-------------------------------------------
 * Class Rule
 * @package app\admin\controller
 * 权限规则增删改查
 * +-------------------------------------------
 */
class Rule extends Check{
    /**
     * @return \think\response\View
     * 权限列表
     */
    public function ruleList(){
        $rule = new Data('auth_rule');
        $get = Request::instance()->get();
        $where = 'id > 0';
        if(!empty($get['search'])){
            $where .= " and title like '%{$get['search']}%'";
            $this->assign('search',$get['search']);
        }
        $list = $rule->selectData($where);
        $list = infinite($list,0,0);
        return view('ruleList',['list'=>$list]);
    }
    /**
     * @return \think\response\View
     * 添加权限规则
     */
    public function ruleAdd(){
        try{
            $rule = new Data('auth_rule');
            if(Request::instance()->isPost()){
                $post = Request::instance()->post();
                $rule_validate = new RuleValidate();
                $rule_validate = $rule_validate->ruleValidate();
                self::validateData($rule_validate['rule'], $rule_validate['message'],$post); //验证数据
                $rule_add_bool = $rule->insertData($post);
                if(!$rule_add_bool){
                    throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
                }
                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $parent_rule = $rule->selectData("p_id = 0","id,title");//获取顶级栏目的数据
        return view('ruleAdd',['parent_rule'=>$parent_rule]);
    }

    /**
     * @return \think\response\View
     * 更新权限规则
     */
    public function ruleSave(){
        $rule = new Data('auth_rule');
        if(Request::instance()->isPost()){
            $post = Request::instance()->post();
            $rule_validate = new RuleValidate();
            $rule_validate = $rule_validate->ruleValidate();
            self::validateData($rule_validate['rule'],$rule_validate['message'],$post);//验证数据
            $rule_save_bool = $rule->updateData($post);
            if($rule_save_bool === false){
                throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $id = empty($get['id']) ? 0 : $get['id'];
        $getOne = $rule->find("id = $id");
        $parent_rule = $rule->selectData("p_id = 0","id,title");//获取顶级栏目的数据
        return view('ruleSave',['parent_rule'=>$parent_rule,'one'=>$getOne]);
    }
}